import Vue from '@/main';
import XhrStatus from '@/constants/xhr-status';
import SHA256 from 'crypto-js/sha256';

// 添加时间戳
export function addUrlTimestamp(config) {
  const timestamp = new Date().getTime();

  const { url, originalUrl } = config;
  const hash = url.indexOf('?') === -1 ? '?' : '&';

  config.url = `${url}${hash}t=${timestamp}`;
  config.originalUrl = `${originalUrl}${hash}t=${timestamp}`;
  return config;
}

// 给头部添加加密字段
export function addHeaderToken(config) {
  const {
    data,
    originalUrl,
    method,
    headers,
  } = config;
  const key = 'KGDUTERPYEG'; // KGD 吴 UTER 彦 YEG 祖
  let body;
  let expireDay;
  switch (method.toUpperCase()) {
    case 'GET':
      expireDay = `${originalUrl}${key}`;
      break;
    case 'PUT':
    case 'POST':
    case 'DELETE':
      body = data ? JSON.stringify(data) : '';
      expireDay = `${body}${originalUrl}${key}`;
      break;
    default:
      break;
  }
  headers['expire-day'] = SHA256(expireDay).toString();
  headers['from'] = "admin";
  return config;
}

// 统一处理 xhr 错误，并提示信息
export function checkStatusAndNotify({ data }) {
  if (!data || typeof data.status === 'undefined') {
    Vue.$toast.error(XhrStatus.error);
    return;
  }
  const errorMsg = XhrStatus[data.status];
  if (errorMsg) {
    Vue.$toast.error(errorMsg);
  }
}
